/**
 * <pre>
 *     author : XML
 *     e-mail : 946891360@qq.com
 *     time   : 2019/06/10
 *     version:
 *     desc   :
 * </pre>
 */

import Types from '../types';
import DataStore, {FLAG_STORAGE} from '../../expand/dao/DataStore'
import {handleData} from '../../action/ActionUtil'

/**
 * 获取最热数据的异步action
 * @param storeName [Java,Android ,IOS...]
 * @param url 对应的url
 * @returns {{type: string, theme: any}}
 */
export function onRefreshPopular(storeName, url, pageSize) {
    return dispatch => {
        dispatch({type: Types.POPULAR_REFRESH, storeNames: storeName});
        let dataStore = new DataStore();
        dataStore.fetchData(url, FLAG_STORAGE.flag_popular)//异步action与数据流
            .then(data => handleData(Types.POPULAR_REFRESH_SUCCESS, dispatch, storeName, data, pageSize))
            .catch(error => {
                console.log(error);
                dispatch({
                    type: Types.POPULAR_REFRESH_FAIL,
                    storeName,
                    error
                })
            })
    };
}

/**
 * 加载更多
 * @param storeName
 * @param pageIndex
 * @param pageSize
 * @param dataArray
 * @param callback
 */
export function onLoadMorePopular(storeName, pageIndex, pageSize, dataArray = [], callback) {
    return dispatch => {
        setTimeout(() => {//模拟网络请求
            if ((pageIndex - 1) * pageSize >= dataArray.length) {//已加载完全部数据
                if (typeof callback === 'function') {
                    callback('no more data!')

                }
                dispatch({
                    type: Types.POPULAR_LOAD_MORE_FAIL,
                    error: 'no more data!',
                    storeName: storeName,
                    pageIndex: --pageIndex,
                    projectModes: dataArray
                })
            } else {
                let max = pageSize * pageIndex > dataArray.length ? dataArray.length : pageSize * pageIndex
                dispatch({
                    type: Types.POPULAR_LOAD_MORE_SUCCESS,
                    storeName,
                    pageIndex,
                    projectModes: dataArray.slice(0, max)
                })
            }
        }, 500)
    };
}


